<?php
/**
  * Musashi - A project manager for music groups and bands
  * Copyright (C) 2010 Daniel Torres
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */

/**
 *  Default page for starting or managing shows.
 *  This same page starts or edits a show, depending on whether a show id (sid)
 *  has been provided, or not. In all cases, it is assumed that the viewer
 *  has modification permisions for the show. Otherwise, default_member should
 *  be used instead.
 *  
 * @package com_musashi
 * @author Daniel Torres
 */
 
// Make sure we have access to this page
defined('_JEXEC') or die ('Restricted access. Sorry');
 
// Add the stylesheet for this page
JHTML::_('stylesheet','base.css','components/com_musashi/views/common/');
JHTML::_('script','dragdrop.js','components/com_musashi/views/common/');
JHTML::_('script','jquery-1.5.min.js','components/com_musashi/views/common/');
JHTML::_('stylesheet','default.css','components/com_musashi/views/shows/tmpl/');

// Get the show id, if any
$showID = JRequest::getInt('sid',-1);

// We'll be needing this model
$model =& $this->getModel();


/**
 *  Checks to see if there is a message from a previous action. Clears the flag if necessary
 */
function getActionResult( $actionFlag )
{
    $session =& JFactory::getSession();
    
    // Get previous message, then clear
    $msg = $session->get($actionFlag,'');
    $session->set($actionFlag,'');
    
    return $msg;
}


?>
<script language="javascript" type="text/javascript">
<!--

// Compatibility mode for jQuery
var _jq = jQuery.noConflict();

// Makes sure the provided date is on the yyyy-mm-dd format
function isValidDate( theDate )
{
    // 1. Check for format
    var dateFormat = /^\d{4}\-\d{2}\-\d{2}$/;
    if( !dateFormat.test(theDate) )
    {
        return false;
    }
    
    // 2. Check for ranges
    var components = theDate.split('-');
    var dateObj    = new Date( components[0], components[1] - 1, components[2] );
        
    if( (dateObj.getFullYear() != components[0]) || (dateObj.getMonth() + 1 != components[1]) || (dateObj.getDate() != components[2]) )
    {
        return false;
    }
    
    return true;
    
    
}

// Validates the base form
function validateBaseForm()
{
    var theForm = document.baseForm;
    
    // All entries must exist
    if( (theForm.name) && (theForm.name.value == "") )
    {
        alert("Please indicate a show name");
        return false;
    }
    
    if( theForm.date.value == "" )
    {
        alert("Please indicate a show date");
        return false;
    }
    
    // Check the date's format
    if(!isValidDate(theForm.date.value))
    {
        alert("Please correct the specified date.\nFormat should be: yyyy-mm-dd");
        return false;
    }
    
    // Configure date and time
    var hour = parseInt(theForm.baseHour.options[theForm.baseHour.selectedIndex].text);
    var min  = parseInt(theForm.baseMinute.options[theForm.baseMinute.selectedIndex].text);
    var date = theForm.date.value;
    
    if( theForm.basePart.options[theForm.basePart.selectedIndex].text == "pm" ){
        hour += 12;
    }
    
    var dateTime = date + ' ' + hour + ':' + min + ':00';
    theForm.datetime.value = dateTime;
    
    return true;    
}

// Sets the vibility value of a component 
// @param componentName Name of the HTML component's id
// @param visibility If true, the component is shown.
function showComponentByID( componentName, visibility )
{
    var component = document.getElementById(componentName);
    if (component)
    {
        if (visibility){
            component.style.display = "block";
        } else {
            component.style.display = "none";
        }
    }
}



-->
</script>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->


<musashiContent id='content' class='body'>
    
    <header id="title" class="body">
        <div class="name">
            <h1><?php if($showID == -1) { echo 'Start a show'; } else { echo 'Configuring your show'; }?></h1>
        </div>
        <div class="description">
        <p>This page allows you to start and configure a new show. Include
        all information available at the moment. You can add or edit any
        details later</p>
        </div>
    </header>
    
    <?php
    
    // -------------------------------------------------------------------------
    // Previous action result
    // -------------------------------------------------------------------------
    $previousMessage = getActionResult('errorMessage');
    if( $previousMessage != '')
    {?>
        <div class="error"><?php echo $previousMessage; ?></div>
    <?php        
    }    
        
    // Get some required information
    $showData  = $model->getShowData($showID);
    $creator   = $model->getShowCreator($showID);
    $venueData = $model->getVenueList();        
        
    // Translate date
    $phpdate  = strtotime($showData['datetime']);
    $dateInfo = date_parse($showData['datetime']);
    $hour     = (int)$dateInfo['hour'];
    $minute   = (int)$dateInfo['minute'];
    $pm       = false;
        
    if($hour > 12){
        $hour -=12;
        $pm   = true;
    }
        
    ?>
        <!-- Extra JS -->
        <script language="javascript" type="text/javascript">
        <!--
        
        // Inits drag-and-drop operations
        function onRegisterDropTargets()
        {
            // Register this page's drop targets
            registerDropTarget('accounted','unaccounted');
                        
        }
        
            
        // Validates the venue
        function validateVenueForm()
        {
            var theForm = document.venueForm;
            
            // Name and address are required
            if ( theForm.name )
            {
                if ( theForm.name.value == "" )
                {
                    alert("Please indicate a name for this venue");
                    return false;                    
                }
                
                if (theForm.name.value.search(/'/i) != -1 )
                {
                    alert("The venue name contains an invalid character [']. Please try again");
                   return false;
                }
            }
            
            if ((theForm.address) && (theForm.address.value == ""))
            {
                alert("Please indicate an address for this venue");
                return false;
            }
            
            // The name must be different from what we already have
            var venueArray = [];
            <?php
                if( is_array($venueData) )
                {
                    foreach ($venueData as $venue )
                    {
                        echo "venueArray.push('".$venue[1]."');";
                    }                        
                }
            ?>
    
            // Test
            if (venueArray.indexOf(theForm.name.value) != -1)
            {
                alert("A venue with the same name exists already. Please choose something different");
                return false;
            }
            
            return true;
        }
        
        // Change the venue to an alternate one, provided by our combo box
        function setNewVenue( cbVenues )
        {
            // Other than zero or the current one
            var newVenue = cbVenues.selectedIndex;
            if( newVenue == 0 )
            {
                cbVenues.selectedIndex = <?php echo $showData['venue']; ?>;
                return;
            }
            
            if ( newVenue != <?php echo $showData['venue']; ?> )
            {
                // Set this as the new value
                newLocation = "<?php echo JRoute::_('index.php?option=com_musashi&controller=shows&task=updateVenue&sid='.$showID.'&rdta='.rand(1,9999),false); ?>" + "&vid=" + newVenue;
                document.location.href = newLocation;
            }
            
        }
        
        // Submits a venue selection using jQuery
        _jq( function() {
            _jq('form[name="venueDisplayForm"]').submit(function(){
                var formData = _jq('form[name="venueDisplayForm"]').serialize();
                
                // Update all required information
                _jq.ajax({
                    type: "POST",
                    url: "<?php echo JRoute::_('index.php?');?>",
                    data: formData,
                    success: function(msg)
                    {
                        alert('data updated');
                    }
                });
                
                return false;            
            });
        });
        
        // Shows the select venue by list form
        _jq(function(){
            _jq('#venue-selection-list').click(function(){
                // Hide the form
                _jq('#newVenue').hide('slow');
                
                // Show the combo
                _jq('#selectVenueByList').show('slow');

            });            
        });
        
        // Shows the new venue form
        _jq(function(){
            _jq('#venue-selection-new').click(function(){
                
                // Hide some
                _jq('#selectVenueByList').hide('slow');
                _jq('#venueUpdate').hide('slow');
                
                // Display some
                _jq('#newVenue').show('slow');                
            });
            
        });
        
        

        -->
        </script>
            

            
        <!-- The gist of it -->
        <div id='show-header'>
            <div class='show-header-title'>
                <h1><?php echo $showData['name'];  ?></h1>
                <h2>Created by <?php echo $creator; ?></h2>
            </div>
            <div class='show-header-date'>
                <h2 style='margin:10px 0 0 0;'><?php echo date("l F jS\, Y",$phpdate);?></h2>
                <h2 style='margin:5px 0 0 0;'><?php echo date("g:i a",$phpdate);?></h2>
            </div>
        </div>
                    
            
        <!-- Basic show information -->
        <section id='show-data'>
            <div id='section-title'>
                <h1>Basic Information</h1>
            </div>
            <form id='form-basic-information' name='baseForm' method='post' onsubmit='return validateBaseForm()' action="<?php echo JRoute::_('index.php?');?>">
                <fieldset class='show-data-left'>
                    <ol>
                        <li>
                            <label for="contact">Main contact</label>
                            <input type="text" id="contact" name="contact" maxlength="45" style="width:160px;" value="<?php echo $showData['contact']; ?>" />
                        </li>
                        <li>
                            <label for="date">Date (yyyy-mm-dd)</label>
                            <?php echo JHTML::_('calendar',date("Y-m-d",$phpdate),'date', 'date', '%Y-%m-%d'); ?>                    
                        </li>                        
                        <li>
                            <label for="time">Time</label>
                            <select name='select-hour' id='baseHour'>
                                <?php
                                for($i = 1; $i<=12; $i++)
                                {
                                    if ($i == $hour){
                                        echo '<option selected>'.$i.'</option>';
                                    } else {
                                        echo '<option>'.$i.'</option>';
                                    }
                                }
                                ?>
                            </select>
                            :
                            <select name='select-minute' id='baseMinute' >>
                                <?php
                                for($i=0; $i<=60; $i+=10)
                                {
                                    if($i == $minute){
                                        echo '<option selected>'.$i.'</option>';
                                    } else {
                                        echo '<option>'.$i.'</option>';
                                    }
                                }
                                ?>
                            </select>
                            /
                            <select name='select-part' id='basePart'>
                                <?php
                                if($pm){
                                    echo '<option>am</option><option selected>pm</option>';
                                } else {
                                    echo '<option selected>am</option><option>pm</option>';
                                }                                
                                ?>
                            </select>                    
                        </li>
                        <li>
                            <label for="cost">Cost</label>
                            <input type="text" id="pay" name="pay" value="<?php echo $showData['pay']; ?>" />
                        </li>
                        <li>
                            <label for="status">Current status</label>
                            <select class="show-basics-form-status" name="status">
                                <?php echo $model->getStatusHTMLCombo($showData['status']); ?>
                            </select>
                        </li>
                    </ol>
                </fieldset>
                <fieldset class='show-data-right'>
                    <label for="notes" style="width:100%; text-align:left;">Notes</label>
                    <textarea name="notes" id="notes" style="width: 80%; height:80%;"><?php echo $showData['notes']; ?></textarea>
                </fieldset>
                <fieldset class='show-data-save'>
                    <input type="submit" name="submit" value="Save changes"/>
                    and notify 
                    <select name='notify'>
                        <?php echo $model->getNotificationTargetsHTMLCombo(); ?>
                    </select>                    
                </fieldset>
                <input type="hidden" name="option"     value="com_musashi" />
                <input type="hidden" name="task"       value="updateShow" />
                <input type="hidden" name="controller" value="shows" />
                <input type="hidden" name="sid"        value="<?php echo $showID; ?>" />
                <input type="hidden" name="datetime"   value="" />                
            </form>
        </section>
        
        <!-- --------------------------------------------------------------- -->
        <!-- Venue -->
        <!-- --------------------------------------------------------------- -->
        <?php
        
        $venueFromList = true;
        
        // Don't select from our list if we have no venues
        if( count($venueData) == 0 )
        {
            $venueFromList = false;
        }
        
        
        ?>
        <a name="venue" style="text-decoration:none;">
        <section id='show-data'>
            <div id='section-title'>
                <h1>Venue</h1>
            </div>
            
            <!-- Venue selection type -------------------------------------- -->
            <form id="venue-input-selection">
                <input type="radio" name="venue-selection" id="venue-selection-list" value="list" <?php
                    if ($venueFromList){
                        echo "checked";
                    } else {
                        echo "disabled";
                    }
                    ?> />Select from a list of existing venues<br/>                    
                <div id="selectVenueByList" <?php
                    if(!$venueFromList){
                        echo "style='display:none'";
                    } else {
                        echo "style='display:block'";
                    } ?>  >
                    <select name="venueSelector" style="margin-left:2em;" onchange="setNewVenue(this);">
                        <option value="0">---Select a venue----</option>
                        <?php
                        foreach( $venueData as $venue )
                        {
                            if($venue[0] == $showData['venue'] ){
                                echo '<option value="'.$venue[0].'" selected>'.$venue[1].'</option>';
                            } else {
                                echo '<option value="'.$venue[0].'">'.$venue[1].'</option>';
                            }
                        }
                        ?>
                    </select><br/>
                </div>
                <input type="radio" name="venue-selection" id="venue-selection-new" value="new" <?php if(!$venueFromList){ echo "checked"; }  ?> />Create a new venue
            </form>
            
            <!-- New venue content ----------------------------------------- -->
            <div id="newVenue" <?php
                    if($venueFromList){
                        echo "style='display:none'";
                    } else {
                        echo "style='display:block'";
                    } ?>  >
                <form id="form-basic-information" name='venueForm' method='post' onsubmit='return validateVenueForm();' action="<?php echo JRoute::_('index.php?');?>">
                    <fieldset class="show-data-left" style="height:16em;">
                        <ol>
                            <li>
                                <label for="name">Venue name</label>
                                <input type="text" id="name" name="name" maxlength="45" style="width:160px;" />
                            </li>
                            <li>
                                <label for="address">Address</label>
                                <input type="text" id="address" name="address" maxlength="45" style="width:160px;" />
                            </li>
                            <li>
                                <label for="contact">Contact</label>
                                <input type="text" id="contact" name="contact" style="width:160px;" />
                            </li>
                            <li>
                                <label for="link">Web link</label>
                                <input type="text" id="link" name="link" maxlength="45" style="width:160px;" />
                            </li>
                        </ol>
                    </fieldset>
                    <fieldset class="show-data-right">
                        <label for="description" style="width:100%; text-align:left;">Description</label>
                        <textarea name="description" id="description" style="width: 80%; height:50%;"></textarea>
                        <br/>
                        <label for="notes" style="width:100%; text-align:left;">Notes</label>
                        <textarea name="notes" id="notes" style="width: 80%; height:50%;"></textarea>
                    </fieldset>
                    <fieldset class='show-data-save'>
                        <input type="submit" name="submit" value="Save venue"/>
                        and notify 
                        <select name='notify'>
                            <?php echo $model->getNotificationTargetsHTMLCombo(); ?>
                        </select>                    
                    </fieldset>
                    <input type="hidden" name="option"     value="com_musashi" />
                    <input type="hidden" name="task"       value="addVenue" />
                    <input type="hidden" name="controller" value="shows" />
                    <input type="hidden" name="sid"        value="<?php echo $showID; ?>" />
                </form>
            </div>
            
            <!-- venue descriptor content ----------------------------------- -->            
            <div id="venueUpdate">                
            <?php
            if ($showData['venue'] != 0 )
            {
                $venueValues = $model->getVenueData( $showData['venue'] );
                ?>
                <form id="form-basic-information" style='height:auto;' name='venueDisplayForm'>
                    <fieldset class="show-data-left">
                        <h2><?php echo $venueValues['name']; ?></h2>
                        <h3><?php echo $venueValues['description']; ?></h3>
                        <h4 style='margin:15px 0 0 0;'><?php echo $venueValues['address']; ?></h4>
                        <h4 style='margin:5px 0 0 0';><b>Contact:</b> <?php echo $venueValues['contact']; ?></h4>
                        <?php if ($venueValues['link'] != "" ){ echo '<h4><a href="'.$venueValues['link'].'">[Link]</a></h4>'; } ?>
                    </fieldset>
                    <fieldset class="show-data-right" style="height:5em;">
                        <label for="notes" style="width:100%; text-align:left;">Notes</label>
                        <textarea name="notes" id="notes" style="width: 80%; height:80%;"><?php echo $venueValues['notes']; ?></textarea>                        
                    </fieldset>
                    <fieldset class='show-data-save' style='padding: 1.5em 0px 0px 33em;'>
                        <input type="submit" id="update" name="submit" value="Update notes"/>
                        and notify 
                        <select name='notify'>
                            <?php echo $model->getNotificationTargetsHTMLCombo(); ?>
                        </select>                    
                    </fieldset>
                    <input type="hidden" name="option"     value="com_musashi" />
                    <input type="hidden" name="task"       value="updateVenueComments" />
                    <input type="hidden" name="controller" value="shows" />
                    <input type="hidden" name="vid"        value="<?php echo $venueValues['id']; ?>" />
                    <input type="hidden" name="sid"        value="<?php echo $showID; ?>" />
                </form>
            <?php    
            }?>
            </div>
        </section>
        </a>
        
        <!-- --------------------------------------------------------------- -->
        <!-- Members -->
        <!-- --------------------------------------------------------------- -->
        <a name="members" style="text-decoration:none;">
        <section id='show-data'>
            <div id='section-title'>
                <h1>Members</h1>
            </div>
            <div id="member-container">
                <h3>Although each member should add him/herself into the list,
                    you can, as the organizer, modify their status. </h3></br>
                <div id="accounted">
                    <form class="member-entry">
                        <h2>Someone</h2>
                        <select>
                            <option>confirmed</option>
                            <option>unsure</option>
                            <option>abscent</option>
                        </select>
                        <select>
                            <option>floorplanner</option>
                            <option>player</option>
                            <option>organizer</option>
                        </select>
                        <input type="button" value="Remove" />
                    </form>
                    <form class="member-entry" style="background-color:#DADADA">
                        <h2>Someone</h2>
                        <select>
                            <option>confirmed</option>
                            <option>unsure</option>
                            <option>abscent</option>
                        </select>
                        <select>
                            <option>floorplanner</option>
                            <option>player</option>
                            <option>organizer</option>
                        </select>
                        <input type="button" value="Remove" />
                    </form>
                </div>
                <div id="unaccounted">
                    <?php
                    // Give me a list with all the members that are not on this show
                    // without including myself
                    
                    
                    
                    
                    ?>
                    <form class="member-entry" id='member-one'
                                draggable="true"
                                ondragstart="onStartDragging(event)"
                                ondragend="onStopDragging(event)">
                        <h2>Someone</h2>
                    </form>
                    <form class="member-entry" id='member-two'
                                draggable="true"
                                ondragstart="onStartDragging(event)"
                                ondragend="onStopDragging(event)">
                        <h2>Someone</h2>
                </div>                
            </div>            
        </section>
        </a>

        <!-- Show design -->
        <a name="design" style="text-decoration:none;">
        <section id='show-data'>
            <div id='section-title'>
                <h1>Show Design</h1>
            </div>
            
        </section>
        </a>
        
        <!-- Clothing and costumes -->
        <a name="clothes" style="text-decoration:none;">
        <section id='show-data'>
            <div id='section-title'>
                <h1>Clothing and Costumes</h1>
            </div>
            
        </section>
        </a>
        
        <!-- Equipment -->
        <a name="equipment" style="text-decoration:none;">
        <section id='show-data'>
            <div id='section-title'>
                <h1>Equipment</h1>
            </div>
            
        </section>
        </a>
        
    <?php   
    }    
    ?>
    
    
    <!-- Footer. Display syndication, and some copyright information -->
    <footer id="footer" class="body">
        <div class="footer-data">
            <h2>The Musashi Project</h2>
            <h3>A Framework for Managing Your Group</h3>
            <p>(c)2010 - The Musashi Project</p>                    
        </div>
    </footer>
    
    
</musashiContent>










